﻿<?php
	require("include/config.php");
	$error = 0;
	if(isset($_GET['id']) == true){
		if(is_numeric($_GET['id']) == false){
			$error = 1;
		}
		if($error == 1){
			header("Location: http://".$_SERVER['HTTP_HOST']);
		}else{
			$validentry = $_GET['id'];
		}
	}else{
		$validentry = 0;
		header("Location: http://".$_SERVER['HTTP_HOST']);
	}
	if(isset($_POST['submit'])){
		$db=mysql_connect($dbhost,$dbuser,$dbpassword);
		mysql_select_db($dbbase,$db);
		$sql="INSERT INTO comments(blog_id,dateposted,username,comments) VALUES("
			.$validentry.", NOW(),'".$_POST['username'].
			"','".$_POST['comments']."');";
		mysql_query($sql);
		header("Location: http://".$_SERVER['HTTP_HOST']."/viewentry.php?id=".$validentry);
	}else{
		
	}
	require("include/header.php");
	if($validentry == 0){
		$sql = "SELECT entries.*, categories.cat from entries,categories ".
			" WHERE entries.cat_id = categories.id 
			AND entries.id = ".$validentry.
			" ORDER BY dateposted DESC LIMIT 1;";
	}else{
		$sql = "SELECT entries.*, categories.cat from entries,categories ".
			" WHERE entries.cat_id = categories.id AND entries.id = ".$validentry.
			" ORDER BY dateposted DESC LIMIT 1;";
		$result = mysql_query($sql);	
		$row = mysql_fetch_array($result);
		echo "<h2>".$row['subject']
			."</h2><br />";
		echo "<i>In <a href='viewcat.php?id=".$row['cat_id']
			."'>".$row['cat'].
			"</a> - Posted on ".date("D jS F Y g.iA",strtotime($row['dateposted']))
			."</i>";
		echo "<p>";
		echo nl2br($row['body']);
		echo "</p>";
		echo "<p>";
		$commsql = "SELECT * FROM comments WHERE blog_id = ".$row['id'].
			" ORDER BY dateposted DESC;";
		$commresult = mysql_query($commsql);
		$numrows_comm = mysql_num_rows($commresult);
		if($numrows_comm == 0){
			echo "<p>No comments.</p>";
		}else{
			echo "(<strong>".$numrows_comm."</strong>) comments :";
			$i = 1;
			while($commrow = mysql_fetch_assoc($commresult)){
				echo "<a name='comment".$i."'>";
				echo "<h3>Comment by ".$commrow['username']." on ".date("D jS F Y G,iA",
					strtotime($commrow['dateposted']))."</h3>";
				echo nl2br($commrow['comments']);
				$i++;
			}
		}
		echo "</p>";
?>
<h3>Leave a message</h3>
<form action="<?php echo "viewentry.php?id=".$validentry; ?>" method="post">
	<table>
		<tr>
			<td>Your name</td>
			<td><input type="text" name="username" /></td>
		</tr>
		<tr>
			<td>Comments</td>
			<td><textarea name="comments" rows="10" cols="50"></textarea></td>
		</tr>
		<tr>
			<td></td>
			<td><input type="submit" name="submit" value="Add comment" /></td>
		</tr>
	</table>
</form>
<?php
	}
	require("include/footer.php");
?>